package cn.yuanqiao.archive.appManager.service.impl;/**
 * @author 赵常飞
 * @date 2024/1/25 16:05
 */

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.common.core.domain.TreeSelect;
import cn.yuanqiao.archive.appManager.mapper.TenantGdfwAndBgqxMapper;
import cn.yuanqiao.archive.appManager.service.ITenantGdfwAndBgqxService;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *@Author: 赵常飞
 *@Date: 2024/1/25 16:05
 *@Description:
 *@Note:
 */
@Service
public class TenantGdfwAndBgqxServiceImpl implements ITenantGdfwAndBgqxService {
    @Autowired
    private TenantGdfwAndBgqxMapper tenantGdfwAndBgqxMapper;

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public List<TreeSelect> selectTreeList(Long categoryId) {
        TenantGdfwAndBgqx yqTrees=new TenantGdfwAndBgqx();
        List<TenantGdfwAndBgqx> list = tenantGdfwAndBgqxMapper.getTreeListfirst(new TenantGdfwAndBgqx().getTableName(),categoryId);
        TreeSelect rootTree = new TreeSelect();
        rootTree.setId(0L);
        rootTree.setLabel("根节点");
        List<TreeSelect> chilTrees = new ArrayList<>();
        for(TenantGdfwAndBgqx yqdaTrees:list){
            TreeSelect chilTree = new TreeSelect();
            chilTree.setId(yqdaTrees.getId());
            chilTree.setLabel(yqdaTrees.getName());
            chilTree.setBgqx(yqdaTrees.getBgqx());
            chilTree.setOrder_no(yqdaTrees.getOrderNo());
            chilTree.setChildren(getchildrens(yqdaTrees.getId(),categoryId));
            chilTrees.add(chilTree);
        }
        rootTree.setChildren(chilTrees);
        List<TreeSelect> treeSelects = new ArrayList<>();
        treeSelects.add(rootTree);
        return treeSelects;
    }

    @Override
    public int addzd(TenantGdfwAndBgqx gdfwAndBgqx) {
        LoginUser user = SecurityUtils.getLoginUser();
        if(user == null){
            user = new LoginUser();
            user.setUserId(1L);
        }
        gdfwAndBgqx.setId(SnowflakeIdGenerator.generateId());
        gdfwAndBgqx.setCreator(user.getUsername());
        gdfwAndBgqx.setCreatorId(user.getUserId());
        gdfwAndBgqx.setCreateTime(DateUtils.getNowDate());
        gdfwAndBgqx.setIsDel(0);
        Integer i=tenantGdfwAndBgqxMapper.addzd(gdfwAndBgqx);
        return 1;
    }

    @Override
    public int editzd(TenantGdfwAndBgqx gdfwAndBgqx) {
        LoginUser user = SecurityUtils.getLoginUser();
        if(user == null){
            user = new LoginUser();
            user.setUserId(1L);
        }
        gdfwAndBgqx.setUpdater(user.getUsername());
        gdfwAndBgqx.setUpdaterId(user.getUserId());
        gdfwAndBgqx.setUpdateTime(DateUtils.getNowDate());
        Integer i=tenantGdfwAndBgqxMapper.editzd(gdfwAndBgqx);
        return 1;
    }

    @Override
    public List<TenantGdfwAndBgqx> gettable(Long parentId,Long categoryId) {
        return tenantGdfwAndBgqxMapper.gettable(parentId,new TenantGdfwAndBgqx().getTableName(),categoryId);
    }

    @Override
    public int addtj(TenantGdfwAndBgqxRule gdfwAndBgqxrule) {
        gdfwAndBgqxrule.setId(SnowflakeIdGenerator.generateId());
        Integer i=tenantGdfwAndBgqxMapper.addtj(gdfwAndBgqxrule);
        return 1;
    }

    @Override
    public int edittj(TenantGdfwAndBgqxRule gdfwAndBgqxrule) {
        Integer i=tenantGdfwAndBgqxMapper.edittj(gdfwAndBgqxrule);
        return 1;
    }

    @Override
    public List<Map<String,Object>> gettjtable(Long zdId,Integer type) {
        return tenantGdfwAndBgqxMapper.gettjtable(zdId,new TenantGdfwAndBgqxRule().getTableName(),new TenantGdfwAndBgqx().getTableName(),new TenantCategory().getTableName(),new TenantMdataList().getTableName(),type);
    }

    @Override
    public TenantGdfwAndBgqx getzd(Long zdid) {
        return tenantGdfwAndBgqxMapper.getzd(zdid,new TenantGdfwAndBgqx().getTableName());
    }

    @Override
    public String gettjsql(Long zdId,Integer type) {
        String sql=" and (";
        List<Map<String,Object>> list=tenantGdfwAndBgqxMapper.gettjtable(zdId,new TenantGdfwAndBgqxRule().getTableName(),new TenantGdfwAndBgqx().getTableName(),new TenantCategory().getTableName(),new TenantMdataList().getTableName(),type);
        for (int i = 0; i <list.size(); i++) {
            String fieldName=list.get(i).get("FIELD_NAME").toString();
            String likepos=list.get(i).get("LIKEPOS").toString();
            String relation=list.get(i).get("RELATION").toString();
            String [] aa=list.get(i).get("KEYWORD").toString().split("\\|");
            if(i==0){
                sql+="(";
            }else{
                sql+=relation;
                sql+="(";
            }
            for (int j = 0; j < aa.length; j++) {
                sql+=fieldName+" like '";
                if("左模糊".equals(likepos)||"模糊".equals(likepos)){
                    sql+="%";
                }
                sql+=aa[j];
                if("右模糊".equals(likepos)||"模糊".equals(likepos)){
                    sql+="%";
                }
                sql+="'";
                if(j<aa.length-1){
                    sql+=" or ";
                }

            }
            sql+=")";
        }
        sql+=")";
        return sql;
    }

    @Override
    public int delete(Long tjid) {
        return tenantGdfwAndBgqxMapper.delete(new TenantGdfwAndBgqxRule().getTableName(),tjid);
    }

    @Override
    public List<String> getfieldbycategoryid(Long categoryId,Integer type) {
        return tenantGdfwAndBgqxMapper.getfieldbycategoryid(new TenantGdfwAndBgqx().getTableName(),new TenantGdfwAndBgqxRule().getTableName(),categoryId,type);
    }

    @Override
    public String getbgqxbyfile(JSONObject json) {
        String databaseId = sqlSessionFactory.getConfiguration().getDatabaseId();

        Integer type=json.getInteger("type");
        Long categoryId=json.getLong("categoryId");
        com.alibaba.fastjson.JSONArray fileNames = json.getJSONArray("fileNames");
        JSONArray fileValues = json.getJSONArray("fileValues");
        List<String> bgqxlist=new ArrayList<>();
        String sql="select count(1) from (select ";
        for (int i = 0; i < fileNames.size(); i++) {
            sql+="'"+fileValues.get(i)+"' as "+fileNames.get(i);
            if(i!=fileNames.size()-1){
                sql+=", ";
            }
        }
        //判断是否是瀚高
        if(databaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode())){
            sql += " ) where 1=1 ";
        }else {
            sql += " from dual) where 1=1 ";
        }
        boolean hasgz=false;//可能存在都没配置具体规则
        List<TenantGdfwAndBgqx> zdlist=tenantGdfwAndBgqxMapper.getzdlist(new TenantGdfwAndBgqx().getTableName(),categoryId);
        for (int i = 0; i < zdlist.size(); i++) {
            String appendsql=gettjsql(zdlist.get(i).getId(),type);
            if(!"and()".equals(appendsql.replace(" ",""))){
                hasgz=true;
                sql+=appendsql;
                Integer count=tenantGdfwAndBgqxMapper.getcount(sql);
                //select count(1) from (select '张三'as title,'李四'as zrz from dual) where 1=1 and ((TITLE like '%张' or TITLE like '%李'))
                //java处理复杂,且难以判断,使用sql最简单
                if(count>0){
                    bgqxlist.add(zdlist.get(i).getBgqx());
                }
            }
        }
        if(!hasgz&&zdlist.size()>0){
            return "失败:归档范围未配置字段规则";
        }
        if(bgqxlist.size()==1){
            return "成功:"+bgqxlist.get(0);
        }else if(bgqxlist.size()>1){//可能匹配多个规则
            // 此处字典值不一定是由数字组成,以字典配置规则排序时,后续维护可能出错,返回多个值以供选择
            String bgqxs=tenantGdfwAndBgqxMapper.getbgqxnames(new TenantSysDictData().getTableName(),bgqxlist);
            return "失败:根据归档范围配置,匹配到多个值,请在保管期限中选择["+bgqxs+"]";
        }
        return null;
    }

    private List<TreeSelect> getchildrens(Long id,Long categoryId) {
        TenantGdfwAndBgqx yqTrees=new TenantGdfwAndBgqx();
        List<TenantGdfwAndBgqx> list = tenantGdfwAndBgqxMapper.getchildrens(id,new TenantGdfwAndBgqx().getTableName(),categoryId);
        List<TreeSelect> chilTrees = new ArrayList<>();
        for(TenantGdfwAndBgqx yqdaTrees:list){
            TreeSelect chilTree = new TreeSelect();
            chilTree.setId(yqdaTrees.getId());
            chilTree.setLabel(yqdaTrees.getName());
            chilTree.setOrder_no(yqdaTrees.getOrderNo());
            chilTree.setBgqx(yqdaTrees.getBgqx());
            chilTree.setChildren(getchildrens(yqdaTrees.getId(),categoryId));
            chilTrees.add(chilTree);
        }
        return chilTrees;
    }
}
